package com.cz.zslu.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间操作
 *
 * @author zhanghaogao
 * @create 2018-01-10 上午9:13
 **/
public class DateUtil {


    /**
     * 时间格式化
     *
     * @param date
     * @param format
     * @return
     */
    public static Date dateParse(String date, String format) throws ParseException {
        SimpleDateFormat dateFormater = new SimpleDateFormat(format);
        return dateFormater.parse(date);
    }


    /**
     * 获取某月天数
     * @param date
     * @return
     */
    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }




    /**
     * 时间格式化
     *
     * @param data
     * @param format
     * @return
     */
    public static String dateFormatToString(Date date, String format) {
        SimpleDateFormat dateFormater = new SimpleDateFormat(format);
        return dateFormater.format(date);
    }

    public static Date dateFormatToDate(Date date, String format) throws ParseException {
        SimpleDateFormat dateFormater = new SimpleDateFormat(format);
        return dateFormater.parse(dateFormater.format(date));
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }


    /**
     * * @param date
     * * @param day 想要获取的日期与传入日期的差值 比如想要获取传入日期前四天的日期 day=-4即可
     * * @return
     */
    public static Date getSomeDay(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);
        return calendar.getTime();
    }

    public static Date getSomeYear(Date date, int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, year);
        return calendar.getTime();
    }

    /**
     * 获取几分钟后的时间
     * @param date
     * @param minute
     * @return
     */
    public static Date getSomeMinute(Date date, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, minute);
        return calendar.getTime();
    }
}
